package cn.com.jbs.course.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.com.jbs.course.service.CoreService;
import cn.com.jbs.course.util.SignUtil;

/**
 * 核心请求处理类
 * 
 * @author liufeng
 * @date 2013-05-18
 */
public class CoreServlet extends HttpServlet {
	private static final long serialVersionUID = 4440739483644821986L;
	boolean istrue = false;
//	private String appid = "wxceb98c137c0360ae";
//	private String appsecret = "8ebee19dcf4181201bfa241b03172679";

	/**
	 * 确认请求来自微信服务器
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 微信加密签名
		String signature = request.getParameter("signature");
		// 时间戳
		String timestamp = request.getParameter("timestamp");
		// 随机数
		String nonce = request.getParameter("nonce");
		// 随机字符串
		String echostr = request.getParameter("echostr");

		PrintWriter out = response.getWriter();
		// 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
		if (SignUtil.checkSignature(signature, timestamp, nonce)) {
			out.print(echostr);
		}
		out.close();
		out = null;
	}

	/**
	 * 处理微信服务器发来的消息
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 将请求、响应的编码均设置为UTF-8（防止中文乱码）
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		// 调用核心业务类接收消息、处理消息
		String respMessage = CoreService.processRequest(request);

		// 响应消息
		PrintWriter out = response.getWriter();
		out.print(respMessage);
		//注释掉自定义菜单，订阅号目前不支持此功能
		/*if(istrue == false){
			istrue=true;
			AccessToken token=WeixinUtil.getAccessToken(appid, appsecret);
			JSONObject obj=WeixinUtil.httpRequest(menu_create_url.replace("ACCESS_TOKEN",token.getToken()), "POST", createMenu());
			System.out.println(obj.toString());
		}*/
		out.close();
	}
	private String createMenu() {
		String menu = " { 	  \"button\":[ 	  { \"type\":\"click\",   \"name\":\"天气预报\",   \"key\":\"1\"  }, "
				+ " {    \"type\":\"click\",    \"name\":\"公交查询\",    \"key\":\"2\"  }, "
				+ " {    \"name\":\"菜单\",    \"sub_button\":[  {        \"type\":\"click\",        \"name\":\"电影排行榜\",        \"key\":\"9\"     },  {      \"type\":\"view\",        \"name\":\"搜索\",        \"url\":\"http://www.soso.com/\"     },     {        \"type\":\"view\",        \"name\":\"视频\",        \"url\":\"http://v.qq.com/\"     }]   }] 		 }";
		return menu;
	}

}